<template>
  <div class="chat-container">
    <!-- 左侧对话列表 -->
    <div class="conversation-sidebar">
      <div class="sidebar-header">  
        <el-button 
          type="primary" 
          :icon="Plus" 
          class="new-conversation-btn"
          @click="handleCreateConversation"
        >
          新建对话
        </el-button>
      </div>

      <div class="conversation-list">
        <div
          v-for="conv in chatStore.conversations"
          :key="conv.id"
          class="conversation-item"
          :class="{ active: conv.id === chatStore.currentConversationId }"
          @click="chatStore.currentConversationId = conv.id"
        >
          <div class="conversation-info">
            <h3>{{ conv.title }}</h3>
          </div>
          <el-button
            v-if="chatStore.conversations.length > 1"
            type="danger"
            :icon="Delete"
            circle
            size="small"
            @click.stop="handleDeleteConversation(conv.id)"
          />
        </div>
      </div>

      <!-- 用户信息区域 -->
      <div class="sidebar-footer">
        <el-dropdown trigger="click" placement="top-start">
          <div class="user-info-card">
            <el-avatar
              :size="40"
              :src="authStore.userInfo?.avatar"
            >
              {{ (String(authStore.userInfo?.id || '')).charAt(0).toUpperCase() || 'U' }}
            </el-avatar>
            <div class="user-info-text">
              <div class="user-name">{{ authStore.userInfo?.id || '未登录用户' }}</div>
              <div class="user-status">在线</div>
            </div>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item disabled>
                {{ authStore.userInfo?.id || '未登录用户' }}
              </el-dropdown-item>
              <el-dropdown-item divided @click="handleLogout">
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-main">

      <div class="message-list" ref="messageListRef">
        <div
          v-for="msg in currentConversation?.messages"
          :key="msg.id"
          class="message-item"
          :class="msg.sender"
        >
          <!-- 头像 -->
          <div class="message-avatar">
            <el-avatar 
              :size="36" 
              :src="msg.sender === 'user' ? authStore.userInfo?.avatar : null"
            >
              <template v-if="msg.sender === 'user'">
                {{ (String(authStore.userInfo?.id || '')).charAt(0).toUpperCase() || 'U' }}
              </template>
              <template v-else>
                <el-icon :size="20"><ChatDotRound /></el-icon>
              </template>
            </el-avatar>
          </div>
          
          <div class="message-content">
            <!-- 统一的消息气泡 -->
            <div class="message-bubble" :class="{ streaming: msg.streaming, 'empty-bot': msg.sender === 'bot' && !msg.content && !msg.reasoning }">
              <!-- 用户消息直接显示内容 -->
              <template v-if="msg.sender === 'user'">
                <span class="typing-text">{{ msg.content }}</span><span v-if="msg.streaming && msg.content" class="streaming-cursor">|</span>
              </template>
              
              <!-- AI消息统一显示格式 -->
              <template v-else>
                <!-- 推理过程（如果存在） -->
                <div v-if="msg.reasoning" class="reasoning-block">
                  <div class="reasoning-header">思考过程:</div>
                  <div class="reasoning-content" :ref="el => { if (msg.streaming && el) reasoningRefs.set(msg.id, el) }">
                    <span class="typing-text">{{ msg.reasoning }}</span><span v-if="msg.streaming && msg.reasoning && !msg.content" class="streaming-cursor">|</span>
                  </div>
                </div>
                
                <!-- 正常消息内容 -->
                <div v-if="msg.content" class="content-block">
                  <div class="markdown-content" v-html="renderMarkdown(msg.content)"></div>
                  <span v-if="msg.streaming && msg.content" class="streaming-cursor">|</span>
                </div>
                
                <!-- 空内容时的加载提示 -->
                <template v-if="msg.streaming && !msg.content && !msg.reasoning">
                  <span class="loading-text">正在思考...</span>
                </template>
              </template>
            </div>
            <div class="message-time">
              {{ formatTime(msg.timestamp) }}
              <span v-if="msg.streaming" class="streaming-indicator">正在输入...</span>
            </div>
          </div>
        </div>

        <div v-if="!currentConversation?.messages?.length" class="empty-message">
          <el-icon :size="60" color="#C0C4CC">
            <ChatDotRound />
          </el-icon>
          <p>开始新的对话吧</p>
        </div>
      </div>

      <!-- ✅ 输入框 + 发送按钮 -->
      <div class="chat-input">
        <!-- 输入框 -->
        <el-input
          v-model="inputText"
          type="textarea"
          :rows="2"
          resize="none"
          placeholder="请输入消息..."
          @keydown.enter.exact.prevent="handleSend"
          @keydown.enter.shift.exact.prevent="inputText += '\n'"
        />

        <!-- 发送按钮 -->
        <el-button
          class="send-button"
          :class="{ sending: isSending }"
          :disabled="isSending"
          type="primary"
          @click="handleSend"
        >
          <!-- 发送中显示小方块 -->
          <template v-if="isSending">
            <div class="sending-dot"></div>
          </template>

          <!-- 默认显示文字 -->
          <template v-else>
            <el-icon><Promotion /></el-icon>
            <span class="send-text">发送</span>
          </template>
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Promotion, ChatDotRound, View } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { useChatStore } from '@/stores/chat'
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import 'highlight.js/styles/github-dark.css'

const router = useRouter()
const authStore = useAuthStore()
const chatStore = useChatStore()

// 初始化 markdown 渲染器
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return '<pre class="hljs"><code>' +
               hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
               '</code></pre>'
      } catch (__) {}
    }
    return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>'
  }
})

// 渲染 markdown 内容
const renderMarkdown = (content) => {
  if (!content) return ''
  
  // ============ 第一阶段：清理原始 Markdown ============
  
  // 1. 去除行尾空格和制表符
  let cleanedContent = content.replace(/[ \t]+$/gm, '')
  
  // 2. 去除开头和结尾的空行
  cleanedContent = cleanedContent.trim()
  
  // 3. 标准化换行符为 \n
  cleanedContent = cleanedContent.replace(/\r\n/g, '\n').replace(/\r/g, '\n')
  
  // 4. 列表之间：移除所有空行
  cleanedContent = cleanedContent.replace(/(^[ \t]*[\*\-\+\d]+[\.\)][ \t]+.+)(\n\s*\n+)(^[ \t]*[\*\-\+\d]+[\.\)][ \t]+)/gm, '$1\n$3')
  
  // 5. 标题前最多保留一个空行
  cleanedContent = cleanedContent.replace(/\n{2,}(^#{1,6}\s)/gm, '\n\n$1')
  
  // 6. 标题后最多保留一个空行
  cleanedContent = cleanedContent.replace(/(^#{1,6}\s.+$)\n{3,}/gm, '$1\n\n')
  
  // 7. 段落之间最多保留一个空行
  cleanedContent = cleanedContent.replace(/\n{3,}/g, '\n\n')
  
  // ============ 第二阶段：渲染 Markdown ============
  
  const rendered = md.render(cleanedContent)
  
  // ============ 第三阶段：清理渲染后的 HTML ============
  
  let cleanedHtml = rendered
  
  // 1. 移除所有空段落标签
  cleanedHtml = cleanedHtml.replace(/<p>\s*<\/p>/g, '')
  
  // 2. 移除标签之间的多余换行和空白
  cleanedHtml = cleanedHtml.replace(/>\s+</g, '><')
  
  // 3. 清理列表之间的所有间隙
  cleanedHtml = cleanedHtml.replace(/<\/(ul|ol)><(ul|ol)>/g, '</$1><$2>')
  
  // 4. 清理标题和列表之间的空段落
  cleanedHtml = cleanedHtml.replace(/<\/(h[1-6])><p><\/p><(ul|ol)>/g, '</$1><$2>')
  cleanedHtml = cleanedHtml.replace(/<\/(ul|ol)><p><\/p><(h[1-6])>/g, '</$1><$2>')
  
  // 5. 清理段落和列表之间的空段落
  cleanedHtml = cleanedHtml.replace(/<\/p><p><\/p><(ul|ol)>/g, '</p><$1>')
  cleanedHtml = cleanedHtml.replace(/<\/(ul|ol)><p><\/p><p>/g, '</$1><p>')
  
  // 6. 清理列表项之间的空段落
  cleanedHtml = cleanedHtml.replace(/<\/li><p><\/p><li>/g, '</li><li>')
  
  // 7. 最终清理：确保没有连续的空标签
  cleanedHtml = cleanedHtml.replace(/(<p><\/p>)+/g, '')
  
  return cleanedHtml.trim()
}
const inputText = ref("")
const isSending = ref(false)
const messageListRef = ref()
const reasoningRefs = new Map()
const currentConversation = computed(() => chatStore.getCurrentConversation())

onMounted(async () => {
  console.log('Chat.vue mounted, auth status:', {
    isLoggedIn: authStore.isLoggedIn,
    hasToken: !!localStorage.getItem('token'),
    userInfo: authStore.userInfo
  })
  
  // 确保用户已登录后再加载对话数据
  // 使用 localStorage.getItem('token') 作为额外检查
  const hasToken = !!localStorage.getItem('token')
  
  if (authStore.isLoggedIn || hasToken) {
    // 如果 store 状态未同步，先同步
    if (!authStore.isLoggedIn && hasToken) {
      console.log('Syncing auth state before loading conversations...')
      authStore.initializeAuth()
    }
    
    try {
      console.log('Loading conversations...')
      await chatStore.loadConversations()
      console.log('Conversations loaded successfully')
    } catch (error) {
      console.error('加载对话失败:', error)
      ElMessage.error('加载对话失败，请刷新页面重试')
    }
  } else {
    console.log('User not logged in, not loading conversations')
  }
})

watch(() => currentConversation.value?.messages, () => {
  nextTick(() => {
    scrollToBottom()
    // 自动滚动推理内容到底部
    currentConversation.value?.messages?.forEach(msg => {
      if (msg.streaming && msg.reasoning) {
        const reasoningContentEl = reasoningRefs.get(msg.id)
        if (reasoningContentEl) {
          reasoningContentEl.scrollTop = reasoningContentEl.scrollHeight
        }
      }
    })
  })
}, { deep: true })

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 等待退出登录完成
    await authStore.logout()
    
    // 显示成功消息
    ElMessage.success('退出登录成功')
    
    // 跳转到登录页
    router.push('/login')
  } catch (error) {
    // 用户取消了退出操作，不做任何处理
    if (error === 'cancel') {
      return
    }
    // 其他错误也显示成功消息，因为本地状态已经清除
    ElMessage.success('退出登录成功')
    router.push('/login')
  }
}

const handleCreateConversation = async () => {
  try {
    await chatStore.createConversation()
    ElMessage.success('创建新对话成功')
  } catch (error) {
    ElMessage.error('创建对话失败')
  }
}

const handleDeleteConversation = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个对话吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await chatStore.deleteConversation(id)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}


const getLastMessage = (conv) => {
  if (conv.messages.length === 0) return '暂无消息'
  return conv.messages[conv.messages.length - 1].content
}

const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

const scrollToBottom = () => {
  if (messageListRef.value) {
    messageListRef.value.scrollTo({
      top: messageListRef.value.scrollHeight,
      behavior: 'smooth'
    })
  }
}


const handleSend = async () => {
  if (!inputText.value.trim() || isSending.value) return;

  const messageContent = inputText.value.trim();
  inputText.value = "";
  isSending.value = true;

  try {
    // 确保有当前对话，如果没有则创建一个
    if (!chatStore.currentConversationId || !chatStore.getCurrentConversation()) {
      await chatStore.createConversation();
    }
    
    // 调用 chatStore 的 sendMessage 方法
    await chatStore.sendMessage(messageContent);
    // 不显示成功消息，因为流式响应会自然显示结果
  } catch (error) {
    console.error('发送消息失败:', error);
    ElMessage.error('发送消息失败: ' + (error.message || '未知错误'));
  } finally {
    isSending.value = false;
  }
};
</script>

<style scoped>
/* 现代化白色主题样式 */
.chat-container {
  display: flex;
  height: 100vh;
  background: linear-gradient(135deg, #f8fafc 0%, #ffffff 100%);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
}

.conversation-sidebar {
  width: 320px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-right: 1px solid rgba(229, 231, 235, 0.6);
  display: flex;
  flex-direction: column;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.02);
}

.sidebar-header {
  padding: 16px 12px;
  border-bottom: 1px solid rgba(229, 231, 235, 0.4);
  background: rgba(255, 255, 255, 0.8);
}

.sidebar-header h2 {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 16px 0;
  letter-spacing: -0.025em;
}

/* 新建对话按钮样式 */
.new-conversation-btn {
  width: 100%;
  height: 44px;
  border-radius: 12px;
  background: linear-gradient(135deg, #8384a1 0%, #777480 100%);
  border: none;
  font-weight: 500;
  font-size: 14px;
  box-shadow: 0 2px 8px rgba(99, 102, 241, 0.25);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.new-conversation-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.35);
  background: linear-gradient(135deg, #5b5ff1 0%, #8257f5 100%);
}

.new-conversation-btn:active {
  transform: translateY(0);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.conversation-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
}

.conversation-list::-webkit-scrollbar {
  width: 4px;
}

.conversation-list::-webkit-scrollbar-track {
  background: transparent;
}

.conversation-list::-webkit-scrollbar-thumb {
  background: rgba(156, 163, 175, 0.3);
  border-radius: 2px;
}

.conversation-item {
  padding: 12px 16px;
  margin: 4px 12px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
}

.conversation-item:hover {
  background: rgba(99, 102, 241, 0.04);
  transform: translateY(-1px);
}

.conversation-item.active {
  background: linear-gradient(135deg, rgba(99, 102, 241, 0.08) 0%, rgba(139, 92, 246, 0.06) 100%);
  border: 1px solid rgba(99, 102, 241, 0.2);
  box-shadow: 0 2px 8px rgba(99, 102, 241, 0.1);
}

.conversation-info {
  flex: 1;
  min-width: 0;
  overflow: hidden;
}

.conversation-info h3 {
  font-size: 15px;
  font-weight: 500;
  color: #111827;
  margin: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  letter-spacing: -0.01em;
  line-height: 1.3;
}

.conversation-info p {
  font-size: 13px;
  color: #6b7280;
  margin: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.4;
}

/* 左侧底部用户信息区域 */
.sidebar-footer {
  padding: 12px;
  border-top: 1px solid rgba(229, 231, 235, 0.4);
  background: rgba(255, 255, 255, 0.8);
}

.user-info-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  background: rgba(249, 250, 251, 0.5);
}

.user-info-card:hover {
  background: rgba(99, 102, 241, 0.06);
  transform: translateY(-1px);
}

.user-info-card :deep(.el-avatar) {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  color: white;
  box-shadow: 0 2px 8px rgba(16, 185, 129, 0.25);
  flex-shrink: 0;
}

.user-info-text {
  flex: 1;
  min-width: 0;
  overflow: hidden;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
  color: #111827;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 2px;
}

.user-status {
  font-size: 12px;
  color: #10b981;
  font-weight: 400;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #ffffff;
  position: relative;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px 24px;
  background: linear-gradient(180deg, #ffffff 0%, #fafbfc 100%);
}

.message-list::-webkit-scrollbar {
  width: 6px;
}

.message-list::-webkit-scrollbar-track {
  background: transparent;
}

.message-list::-webkit-scrollbar-thumb {
  background: rgba(156, 163, 175, 0.3);
  border-radius: 3px;
}

.message-item {
  display: flex;
  margin-bottom: 10px;
  align-items: flex-start;
  gap: 10px;
}

.message-item.bot {
  margin-top: -14px;
}

.message-item.user {
  flex-direction: row-reverse;
}

.message-item.bot {
  flex-direction: row;
}

.message-avatar {
  flex-shrink: 0;
  margin-top: 4px;
}

.message-avatar :deep(.el-avatar) {
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  color: white;
  box-shadow: 0 2px 8px rgba(99, 102, 241, 0.25);
  transition: transform 0.2s ease;
}

.message-item.user .message-avatar :deep(.el-avatar) {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  box-shadow: 0 2px 8px rgba(16, 185, 129, 0.25);
}

.message-content {
  max-width: 70%;
  display: flex;
  flex-direction: column;
}

.message-bubble {
  border-radius: 8px;
  word-wrap: break-word;
  white-space: pre-wrap;
  font-size: 14px;
  line-height: 1.5;
  position: relative;
}

.message-item.user .message-bubble {
  background: #b0b8c1;
  color: #000000;
  border-bottom-right-radius: 4px;
  padding: 6px 10px;
}

.message-item.bot .message-bubble {
  background: #e2e8f0;
  color: #000000;
  border-bottom-left-radius: 4px;
  padding: 6px 10px;
}

.message-time {
  font-size: 10px;
  color: #9ca3af;
  margin-top: 2px;
  font-weight: 400;
}

.message-item.user .message-time {
  text-align: right;
}

/* 推理块样式 */
.reasoning-block {
  background: rgba(99, 102, 241, 0.15);
  border-left: 3px solid #6366f1;
  margin: 0 0 8px 0;
  border-radius: 4px;
  color: #000000;
  overflow: hidden;
}

/* 推理块标题 - 固定在顶部 */
.reasoning-header {
  font-size: 12px;
  font-weight: 600;
  color: #6366f1;
  padding: 6px 8px 4px 8px;
  background: rgba(99, 102, 241, 0.08);
  border-bottom: 1px solid rgba(99, 102, 241, 0.2);
  position: sticky;
  top: 0;
  z-index: 1;
}

/* 推理内容区域 - 可滚动 */
.reasoning-content {
  padding: 4px 8px;
  font-size: 13px;
  line-height: 1.4;
  max-height: 150px;
  overflow-y: auto;
  overflow-x: hidden;
  word-wrap: break-word;
}

/* 推理内容滚动条样式 */
.reasoning-content::-webkit-scrollbar {
  width: 6px;
}

.reasoning-content::-webkit-scrollbar-track {
  background: rgba(99, 102, 241, 0.08);
  border-radius: 3px;
}

.reasoning-content::-webkit-scrollbar-thumb {
  background: rgba(99, 102, 241, 0.4);
  border-radius: 3px;
}

.reasoning-content::-webkit-scrollbar-thumb:hover {
  background: rgba(99, 102, 241, 0.6);
}

/* 内容块样式 */
.content-block {
  padding: 0;
  margin: 0;
  color: #000000;
}

/* Markdown 内容样式 */
.markdown-content {
  line-height: 1.5;
  color: #000000;
  word-wrap: break-word;
  font-size: 14px;
}

.markdown-content :deep(*:first-child) {
  margin-top: 0 !important;
}

.markdown-content :deep(*:last-child) {
  margin-bottom: 0 !important;
}

/* 标题样式 */
.markdown-content :deep(h1),
.markdown-content :deep(h2),
.markdown-content :deep(h3),
.markdown-content :deep(h4),
.markdown-content :deep(h5),
.markdown-content :deep(h6) {
  margin: 6px 0 3px 0;
  font-weight: 600;
  line-height: 1.3;
  color: #1f2937;
}

/* 列表后接标题：减少上边距 */
.markdown-content :deep(ul + h1),
.markdown-content :deep(ul + h2),
.markdown-content :deep(ul + h3),
.markdown-content :deep(ul + h4),
.markdown-content :deep(ul + h5),
.markdown-content :deep(ul + h6),
.markdown-content :deep(ol + h1),
.markdown-content :deep(ol + h2),
.markdown-content :deep(ol + h3),
.markdown-content :deep(ol + h4),
.markdown-content :deep(ol + h5),
.markdown-content :deep(ol + h6) {
  margin-top: 6px !important;
}

.markdown-content :deep(h1:first-child),
.markdown-content :deep(h2:first-child),
.markdown-content :deep(h3:first-child),
.markdown-content :deep(h4:first-child),
.markdown-content :deep(h5:first-child),
.markdown-content :deep(h6:first-child) {
  margin-top: 0;
}

/* 标题后的元素间距 */
.markdown-content :deep(h1 + *),
.markdown-content :deep(h2 + *),
.markdown-content :deep(h3 + *),
.markdown-content :deep(h4 + *),
.markdown-content :deep(h5 + *),
.markdown-content :deep(h6 + *) {
  margin-top: 3px !important;
}

.markdown-content :deep(h1) {
  font-size: 1.5em;
  border-bottom: 2px solid #e5e7eb;
  padding-bottom: 3px;
}

.markdown-content :deep(h2) {
  font-size: 1.3em;
  border-bottom: 1px solid #e5e7eb;
  padding-bottom: 2px;
}

.markdown-content :deep(h3) {
  font-size: 1.15em;
}

.markdown-content :deep(h4) {
  font-size: 1.05em;
}

/* 段落样式 */
.markdown-content :deep(p) {
  margin: 0;
  line-height: 1.5;
}

/* 段落之间的间距 */
.markdown-content :deep(p + p) {
  margin-top: 0.3em;
}

/* 段落后有其他元素时添加小间距 */
.markdown-content :deep(p + *:not(p)) {
  margin-top: 0.4em;
}

/* 其他元素后接段落的间距 */
.markdown-content :deep(*:not(p) + p) {
  margin-top: 0.3em;
}

/* 列表样式 */
.markdown-content :deep(ul),
.markdown-content :deep(ol) {
  margin: 2px 0;
  padding-left: 20px;
  display: block;
  line-height: 1.4;
}

/* 标题后接列表：紧凑间距 */
.markdown-content :deep(h1 + ul),
.markdown-content :deep(h1 + ol),
.markdown-content :deep(h2 + ul),
.markdown-content :deep(h2 + ol),
.markdown-content :deep(h3 + ul),
.markdown-content :deep(h3 + ol),
.markdown-content :deep(h4 + ul),
.markdown-content :deep(h4 + ol),
.markdown-content :deep(h5 + ul),
.markdown-content :deep(h5 + ol),
.markdown-content :deep(h6 + ul),
.markdown-content :deep(h6 + ol) {
  margin-top: 2px !important;
}

/* 列表之间无间距 - 强制清除所有可能的间距 */
.markdown-content :deep(ul + ul),
.markdown-content :deep(ul + ol),
.markdown-content :deep(ol + ul),
.markdown-content :deep(ol + ol) {
  margin-top: 0 !important;
  margin-bottom: 0 !important;
}

/* 清除列表前后可能的空白文本节点 */
.markdown-content :deep(ul:empty),
.markdown-content :deep(ol:empty) {
  display: none;
}

/* 列表项后接其他元素（非列表） */
.markdown-content :deep(ul + *:not(li):not(ul):not(ol)),
.markdown-content :deep(ol + *:not(li):not(ul):not(ol)) {
  margin-top: 0.4em;
}

/* 确保列表前的元素与列表之间有适当间距 */
.markdown-content :deep(*:not(ul):not(ol):not(li) + ul),
.markdown-content :deep(*:not(ul):not(ol):not(li) + ol) {
  margin-top: 0.4em;
}

/* 防止列表内部出现多余间距 */
.markdown-content :deep(ul p),
.markdown-content :deep(ol p) {
  margin: 0 !important;
  display: inline;
}

.markdown-content :deep(li) {
  margin: 0;
  line-height: 1.4;
  padding: 1px 0;
}

.markdown-content :deep(li > p) {
  margin: 0;
  display: inline;
}

.markdown-content :deep(li + li) {
  margin-top: 1px;
}

/* 嵌套列表 */
.markdown-content :deep(li > ul),
.markdown-content :deep(li > ol) {
  margin: 2px 0;
}

/* 行内代码样式 */
.markdown-content :deep(code) {
  background: rgba(99, 102, 241, 0.1);
  color: #6366f1;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 0.9em;
}

/* 代码块样式 */
.markdown-content :deep(pre) {
  background: #1e293b;
  border-radius: 6px;
  padding: 8px 10px;
  overflow-x: auto;
  margin: 4px 0;
}

.markdown-content :deep(pre code) {
  background: transparent;
  color: #e2e8f0;
  padding: 0;
  border-radius: 0;
  font-size: 0.85em;
  line-height: 1.4;
}

/* 引用块样式 */
.markdown-content :deep(blockquote) {
  border-left: 3px solid #6366f1;
  margin: 4px 0;
  padding: 4px 8px;
  color: #4b5563;
  background: rgba(99, 102, 241, 0.05);
  border-radius: 0 4px 4px 0;
}

.markdown-content :deep(blockquote p) {
  margin: 0;
  line-height: 1.4;
}

/* 链接样式 */
.markdown-content :deep(a) {
  color: #6366f1;
  text-decoration: none;
  transition: color 0.2s;
}

.markdown-content :deep(a:hover) {
  color: #4f46e5;
  text-decoration: underline;
}

/* 表格样式 */
.markdown-content :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin: 4px 0;
  font-size: 0.88em;
  border: 2px solid #cbd5e1;
}

.markdown-content :deep(table th),
.markdown-content :deep(table td) {
  border: 1px solid #cbd5e1;
  padding: 4px 8px;
  text-align: left;
  line-height: 1.4;
}

.markdown-content :deep(table th) {
  background: #f1f5f9;
  font-weight: 600;
  color: #1f2937;
  padding: 5px 8px;
  border: 1px solid #94a3b8;
}

.markdown-content :deep(table tr:nth-child(even)) {
  background: #f8fafc;
}

.markdown-content :deep(table tbody tr:hover) {
  background: #f1f5f9;
}

.markdown-content :deep(table p) {
  margin: 0;
  line-height: 1.4;
}

/* 分割线样式 */
.markdown-content :deep(hr) {
  border: none;
  border-top: 1px solid #e5e7eb;
  margin: 8px 0;
}

/* 图片样式 */
.markdown-content :deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 6px;
  margin: 6px 0;
}

/* 加粗和斜体 */
.markdown-content :deep(strong) {
  font-weight: 600;
  color: #1f2937;
}

.markdown-content :deep(em) {
  font-style: italic;
}

/* 删除线 */
.markdown-content :deep(del) {
  text-decoration: line-through;
  color: #6b7280;
}

/* 加载文本样式 */
.loading-text {
  color: #6366f1;
  font-style: italic;
  font-size: 13px;
}

/* 流式消息样式 */
.message-bubble.streaming {
  position: relative;
}

.typing-text {
  display: inline;
}

.streaming-cursor {
  display: inline-block;
  animation: blink 1s infinite;
  font-weight: bold;
  color: #6366f1;
  margin-left: 1px;
  vertical-align: baseline;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0; }
}

.streaming-indicator {
  color: #6366f1;
  font-size: 9px;
  margin-left: 6px;
  font-style: italic;
}

.empty-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #9ca3af;
}

.empty-message p {
  margin-top: 16px;
  font-size: 16px;
  font-weight: 400;
}

.chat-input {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 24px;
  border-top: 1px solid rgba(229, 231, 235, 0.4);
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
}

.chat-input :deep(.el-textarea) {
  flex: 1;
  display: flex;
  align-items: center;
}

.chat-input :deep(.el-textarea__inner) {
  border: 1px solid rgba(229, 231, 235, 0.6);
  border-radius: 14px;
  padding: 12px 16px;
  font-size: 14px;
  line-height: 1.4;
  resize: none;
  background: #ffffff;
  transition: all 0.2s ease;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.02);
  height: 80px;
  box-sizing: border-box;
}

.chat-input :deep(.el-textarea__inner):focus {
  border-color: #6366f1;
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

/* 发送按钮现代化样式 */
.send-button {
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 90px;
  height: 44px;
  border-radius: 14px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  cursor: pointer;
  background: linear-gradient(135deg, #828296 0%, #a8a2b6 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
  font-weight: 500;
  flex-shrink: 0;
}

.send-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(99, 102, 241, 0.4);
}

.send-text {
  margin-left: 6px;
  font-size: 13px;
}

/* 发送中状态 */
.send-button.sending {
  width: 50px;
  min-width: 50px;
  height: 50px;
  border-radius: 50%;
  padding: 0;
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  transform: scale(1);
}

.send-button:active {
  transform: scale(0.95);
}

/* 发送动画 */
.sending-dot {
  width: 14px;
  height: 14px;
  background: linear-gradient(135deg, #ffffff, rgba(255, 255, 255, 0.8), #ffffff);
  position: relative;
  transform: rotate(0deg);
  animation: rotate-glow 1.2s linear infinite, scale-pulse 1s ease-in-out infinite;
  border-radius: 3px;
}

@keyframes rotate-glow {
  0% {
    transform: rotate(0deg);
    box-shadow: 0 0 6px 2px rgba(255, 255, 255, 0.8),
                0 0 12px 4px rgba(99, 102, 241, 0.6);
  }
  50% {
    transform: rotate(180deg);
    box-shadow: 0 0 12px 4px rgba(99, 102, 241, 0.9),
                0 0 20px 8px rgba(255, 255, 255, 0.8);
  }
  100% {
    transform: rotate(360deg);
    box-shadow: 0 0 6px 2px rgba(255, 255, 255, 0.8),
                0 0 12px 4px rgba(99, 102, 241, 0.6);
  }
}

@keyframes scale-pulse {
  0%, 100% {
    transform: scale(1) rotate(0deg);
  }
  50% {
    transform: scale(1.1) rotate(180deg);
  }
}

.send-button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .conversation-sidebar {
    width: 280px;
  }
  
  .user-menu-float {
    top: 12px;
    right: 16px;
  }
  
  .message-list {
    padding: 56px 20px 20px 20px;
  }
  
  .chat-input {
    padding: 20px 24px;
  }
}
</style>
